package com.nc.delivery_project.client.user_details;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.nc.delivery_project.client.ClientFactory;
import com.nc.delivery_project.client.request.UserRequest;
import com.nc.delivery_project.shared.proxy.RoleProxy;
import com.nc.delivery_project.shared.proxy.UserProxy;

import java.util.List;

/**
 * Created by miroshnik on 1/9/2015.
 */
public class UserDetailsActivity extends AbstractActivity implements UserDetailsPresenter {
    
    private UserDetailsView view;
    private ClientFactory clientFactory;
    
    private UserProxy user;
    
    private List<RoleProxy> roles;

    private int userId;
    
    private UserRequest updateRequest;
    
    private int fetchedCount;
    
    public UserDetailsActivity(UserDetailsPlace place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
        parseToken(place.getToken());
        updateRequest = clientFactory.getRequestFactory().createUserRequest();
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        fetchRoles();
        fetchUser(userId);
        
        if (view == null) {
            view = new UserDetailsView();
        }
        
        view.setPresenter(this);
        panel.setWidget(view);
        view.start();
        
        view.userIdLbl.setText(String.valueOf(userId));

        initButtonHandlers();
    }

    @Override
    public void loadUserDetails(UserProxy user) {
        view.userIdLbl.setText(String.valueOf(user.getId()));
        view.emailTxtBox.setText(user.getEmail());
    }

    @Override
    public void update(UserProxy user) {
        updateRequest.update(user).fire();
        Window.Location.reload();
    }

    @Override
    public void delete(int userId) {
        clientFactory.getRequestFactory().createUserRequest().delete(userId).fire();
    }

    @Override
    public void fillRoleDropBox(List<RoleProxy> roles) {
        for (int i = 0; i < roles.size(); i++) {
            RoleProxy role = roles.get(i);
            view.roleLstBox.addItem(role.getTitle(), String.valueOf(role.getId()));
            if (role.getId() == user.getRole().getId())
                view.roleLstBox.setItemSelected(i, true);
        }
    }

    @Override
    public void goTo(Place place) {
        clientFactory.getPlaceController().goTo(place);
    }

    @Override
    public ClientFactory getClientFactory() {
        return clientFactory;
    }
    
    private void initButtonHandlers() {
        view.saveBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                user.setEmail(view.emailTxtBox.getText());
                user.setRole(roles.get(view.roleLstBox.getSelectedIndex()));
                update(user);
            }
        });

        view.removeBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                delete(user.getId());
            }
        });

        view.resetPassBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                user.setPassword("0000");
                update(user);
            }
        });
    }
    
    private void fetchRoles() {
        clientFactory.getRequestFactory().createRoleRequest().read().fire(new Receiver<List<RoleProxy>>() {
            @Override
            public void onSuccess(List<RoleProxy> response) {
                GWT.log("roles fetched");
                roles = response;

                if (++fetchedCount == 2) fillView();
            }
        });
    }
    
    private void fetchUser(int id) {
        UserRequest userRequest = clientFactory.getRequestFactory().createUserRequest();
        userRequest.read(id).with("role").fire(new Receiver<UserProxy>() {
            @Override
            public void onSuccess(UserProxy response) {
                GWT.log("user fetched");
                user = updateRequest.edit(response);
                
                if (++fetchedCount == 2) fillView();
            }
        });
    }
    
    private void fillView() {
        fillRoleDropBox(roles);
        loadUserDetails(user);
    }
    
    private void parseToken(String token) {
        try {
            userId = Integer.parseInt(token);
        } catch (NumberFormatException e) {
            Window.alert("Unknown Token");
        }
    }
}
